// todo仓库
import { defineStore } from "pinia";
import {ref, computed} from "vue"


// 定义并导出仓库
export const useTodoStore = defineStore("tode", () => {
    // 任务列表
    const todos = ref([
        {id: 1, text: "Buy milk", finished: false},
        {id: 1, text: "Buy books", finished: true},
        {id: 1, text: "Buy eggs", finished: false},
        {id: 1, text: "Buy apples", finished: false},
    ])    
    // 全选属性
    const isAll = computed({
        // 小选全部选中则全选自动生效
        get() {
            return todos.value.every((item) => item.finished)
        },
        // 点击全选则所有选中，取消全选则所有取消
        set(newVal) {
            todos.value.forEach((item) => {
                item.finished = newVal
            })
        }
    })
    // 未完成任务个数
    const unfinishedCount = computed(() => {
        return todos.value.filter((item) => !item.finished).length
    })
    // 视图状态
    const type = ref('All')

    // 删除单个任务
    const del = (i) => {
        todos.value.splice(i, 1)
    }
    // 新增单个任务
    const add = (text) => {
        todos.value.push({
            id: Date.now(),
            text,
            finished: false
        })
    }
    // 清除所有已完成的任务
    const clear = () => {
        todos.value = todos.value.filter((item) => !item.finished)
    }
    // 修改视图状态
    const modifyType = (newType) => {
        type.value = newType
    }
    // 根据视图状态展示对应的数据
    const show = () => {
        if(type.value === "All") {
            // 全部内容
            return todos.value
        } else if (type.value === "Active") {
            // 未完成
            return todos.value.filter((item) => !item.finished)
        } else if (type.value = "Completed") {
            // 已完成
            return todos.value.filter((item) => item.finished)
        }
    }
    return {
        todos,
        isAll,
        unfinishedCount,
        type,
        del,
        add,
        clear,
        modifyType,
        show,
    }
})





